import { HOST } from "@lgq/config";
import { hideLoading, showLoading } from "@lgq/pages/components/loading";
import axios, { AxiosError, AxiosResponse } from "axios";
import storage from "@lgq/utils/storage";
import { message } from "antd";
import { config } from "process";

const instance = axios.create({
  baseURL: HOST,
  timeout: 5000,
  withCredentials: true,
});

//添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (config.showLoading === true) {
      showLoading();
    }
    const token = storage.get("token");
    if (token) {
      config.headers["token"] = token;
    }

    return config;
  },
  (error: AxiosError) => {
    hideLoading();
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    hideLoading();
    //是否登录  跳转到登录页
    //token 过期 跳转到登录页
    //处理业务异常
    const data = response.data;
    const code = data.code;
    if (code != 200) {
      hideLoading();
      if (response.config.showError === false) {
        return Promise.reject(data);
      } else {
        message.error(data.message);
        return Promise.reject(data);
      }
    }
    return data.data;
  },
  (error: AxiosError) => {
    hideLoading();
    return Promise.reject(error);
  }
);

export default instance;
